package com.ddzh.consumer.web;

import com.ddzh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.Random;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    private static int count=0;//维护请求次数
  
    @GetMapping("{id}")
    public User queryById(@PathVariable("id") String username){
//        String url = "http://localhost:8081/user/"+username;

//        count++;
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        //如果我有多个service
//        int index=0;
//        if (count>0){
//            index = count % instances.size();
//        }
//        ServiceInstance serviceInstance = instances.get(index);
//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/"+username;

        String url = "http://user-service/user/"+username;
        System.out.println("url = " + url);

        User userMap = restTemplate.getForObject(url, User.class);
        System.out.println(userMap);
        return userMap;
    }
}